package com.lakeworks.common.utils.bean;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.util.List;

public class DeepCopyUtil {

    /**
     * 对象深拷贝
     *
     * @param sourceObject 源对象
     * @param resultClass  目标对象class
     * @return 目标对象
     */
    public static <FromType, ToType> ToType transform(FromType sourceObject, Class<ToType> resultClass) {
        ParserConfig.getGlobalInstance().setAsmEnable(false);
        return JSON.parseObject(JSON.toJSONString(sourceObject), resultClass);
    }

    /**
     * list深拷贝
     *
     * @param sourceList  源对象list
     * @param resultClass 目标对象class
     * @return 目标对象list
     */
    public static <FromType, ToType> List<ToType> transformList(List<FromType> sourceList, Class<ToType> resultClass) {
        ParserConfig.getGlobalInstance().setAsmEnable(false);
        return JSON.parseArray(JSON.toJSONString(sourceList), resultClass);
    }

    /**
     * @param sourceObject 源对象
     * @param resultClass  目标对象class
     * @param features     json格式转换类型
     * @return 目标对象
     */
    public static <FromType, ToType> ToType transform(FromType sourceObject, Class<ToType> resultClass, SerializerFeature... features) {
        ParserConfig.getGlobalInstance().setAsmEnable(false);
        return JSON.parseObject(JSON.toJSONString(sourceObject, features), resultClass);
    }

    /**
     * @param sourceList  源对象list
     * @param resultClass 目标对象class
     * @param features    json格式转换类型
     * @return 目标对象list
     */
    public static <FromType, ToType> List<ToType> transformList(List<FromType> sourceList, Class<ToType> resultClass, SerializerFeature... features) {
        ParserConfig.getGlobalInstance().setAsmEnable(false);
        return JSON.parseArray(JSON.toJSONString(sourceList, features), resultClass);
    }
}
